package com.wyq.action;


import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.servlet.ServletContext;

import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.wyq.bean.Audience;
import com.wyq.bean.AudienceQInfo;
import com.wyq.service.AudienceService;
import com.wyq.service.MailInfoService;
import com.wyq.service.ShowInfoService;
import com.wyq.util.PropertiesUtil;
import com.wyq.util.StringUtil;

public class AudienceRegisterAction extends ActionSupport {
	private AudienceService audienceService;
	private ShowInfoService showInfoService;
	private MailInfoService mailInfoService;
	private Audience audience;
	private String questioninfo;
	private String emails;
	
	private String source;//展会渠道
	private Map showInfo;//展会信息
	
/*	private String ToEmail1;
	private String ToEmail2;
	private String ToEmail3;
	private String ToEmail4;
	private String ToEmail5;*/
	
	@Override
	public String execute(){
		try {
			//获取展会信息
			getShowInfoId(); 
			
			//获取展会信息错误
			if(null == showInfo){
				//未设置展会信息
				return ERROR;
			}
			
			ServletContext context=ServletActionContext.getServletContext();
			//将接收的字符串保存在问卷调查表中
			//System.out.println("questioninfo" + questioninfo);
			questioninfo = questioninfo.replaceAll(",}", "}");
			questioninfo = questioninfo.replaceAll(",]", "]");
			AudienceQInfo audienceQInfo = new AudienceQInfo();
			
			audienceQInfo.setQInfo(questioninfo);
			audienceQInfo.setAvailable(1);
			audienceQInfo.setAudience(audience);
			audience.getAudienceQInfos().add(audienceQInfo);
			audience.setAudience_isAvailable(1);
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date = new Date();
			audience.setAudience_registerDate(sdf.format(date).toString());
			audience.setShow_id(showInfo.get("id").toString());
			//query.setLockMode( " user " ,LockMode.UPGRADE);  
			
			//查询展会信息
			List showInfoList = new ArrayList();
			//Map showInfo = null;
			//服务器邮箱从数据库查询
			List mailInfoList = new ArrayList();
			Map mailInfo = null;
			//得到数据库的ID的最大值
			List audienceList = new ArrayList();
			Map audienceInfo = null;
			
			//注册用户信息
			audienceList = audienceService.getAudienceMaxID();
			int audience_id = 0;
			if(audienceList.size() > 0){
				audienceInfo = (Map)audienceList.get(0);
				if(null != audienceInfo.get("id")){
					audience_id = Integer.parseInt(audienceInfo.get("id").toString()) + 1;
				}else{
					audience_id = 1;
				}
			}
			
			audience.setId(audience_id);
			String audience_name = audience.getAudience_name();
			String audience_sex = audience.getAudience_sex();
			String audience_company = audience.getAudience_company();
			
			//保存用户
    		audienceService.saveAudience(audience);
			
			String fromMail = "";
			String fromMailPassword = "";
			String toMail = "";
			String fromMailHost = "";
			
			String showName = "";
			String showCompany = "";
			String showTime = "";
			String showAddress = "";
			String showTel = "";
			String showFax = "";
			String showEmail = "";
		    
			showName = showInfo.get("showName").toString();
			showCompany = showInfo.get("showCompany").toString();
			showTime = showInfo.get("showTime").toString();
			showAddress = showInfo.get("showAddress").toString();
			showTel = showInfo.get("showTel").toString();
			showFax = showInfo.get("showFax").toString();
			showEmail = showInfo.get("showEmail").toString();
			
			//发送邮件的邮箱信息
			mailInfoList = mailInfoService.getMailInfo();
			if(mailInfoList.size() <= 0){
				//未设置发送邮信息的邮箱
				return ERROR;
			}
			//当前可用的服务邮箱有且只有一个
			mailInfo = (Map)mailInfoList.get(0);
			fromMail = mailInfo.get("mailServerAddress").toString();
			fromMailPassword = mailInfo.get("mailServerPassword").toString();
			fromMailHost = "smtp." + (fromMail.split("@"))[1];
			
		
			//登记用户的邮箱
			toMail = audience.getAudience_Email();
			//System.out.println("toMail:::::::" + toMail);
			
			//发送邮件
			HtmlEmail email = new HtmlEmail();
			email.setHostName(fromMailHost);
			email.setAuthentication(fromMail, fromMailPassword);
			email.setFrom(fromMail);
			Vector<InternetAddress> emailV = new Vector<InternetAddress>();
			InternetAddress to = new InternetAddress(toMail);
			emailV.add(to);
			email.setTo(emailV);
			email.setCharset("UTF-8");
			email.setSubject("欢迎参加"+showInfo.get("showName")+"展会");
			//System.out.println("path="+context.getRealPath("/"));
			File img = new File(context.getRealPath("/")+"/images/title.jpg");
			if(null != showInfo.get("hearderImgPath")){
				img = new File(context.getRealPath("/")+showInfo.get("hearderImgPath").toString());
			}
			
			StringBuffer buffer = new StringBuffer();  
    		 
    		 //buffer.append("<center style='font-size: 10pt;'>");
			buffer.append("<table width='800px' align='center' cellpadding='0' cellspacing='0' style='font-size: 10pt;width:679px; margin:0 auto; background-color:#FFF'>");
			buffer.append("<tr><td width='800px' height='200px'><img src='cid:"+email.embed(img)+"' width='800' height='200'></td></tr>");
			buffer.append("<tr>");
			buffer.append("<td bgcolor='#FFFFFF' class='fontblack'>");
			buffer.append("<table cellpadding='2' cellspacing='2' style='border:1px solid #999999; padding:10px' width='800px'>");
			/////////
			buffer.append("<tr>");
			buffer.append("<td>");
			buffer.append("尊敬的" + audience_name);
			if(audience_sex.equals("0")){
				buffer.append("先生");
			}else if(audience_sex.equals("1")){
				
				buffer.append("女士");
			}
			buffer.append("：您好");
			buffer.append("</td>");
			buffer.append("</tr>");
			buffer.append("<tr><td height='5px'></td></tr>");
			buffer.append("<tr>");
			buffer.append("<td style='padding-left: 20px'>感谢您注册参观<b>" + showName + "</b>，您的预登记信息已经被正式确认！</td>");
			buffer.append("</tr>");
			buffer.append("<tr><td height='5px'></td></tr>");
			buffer.append("<tr>");
			buffer.append("<td style='padding-left: 20px'>");
			buffer.append("请仔细核对以下参观信息，并打印出此参观确认函(务必可以清晰地看到卡号)，至展会现场预登记观众接待处出示此参观确认函及参观人有效证件(身份证或两张名片均可)，快速换取观众胸卡进入参观。");
			buffer.append("</td>");
			buffer.append("</tr>");
			buffer.append("</table>");
			buffer.append("</td>");
			buffer.append("</tr>");
			buffer.append("<tr>");
			buffer.append("<td height='10px'></td>");
			buffer.append("</tr>");
			buffer.append("<tr>");
			buffer.append("<td>");
			buffer.append("<table cellpadding='2' cellspacing='2' style='border:1px solid #999999; padding:10px' width='800px'>");
			buffer.append("<tr height='30px'>");
			buffer.append("<td align='center'>");
			buffer.append("<b style='font-size: 18px;'>" + showName + "</b>");
			buffer.append("</td>");
			buffer.append("</tr>");
			buffer.append("<tr>");
			buffer.append("<td>");
			buffer.append("<b>专业参观时间：</b>"+showTime);
			buffer.append("</td>");
			buffer.append("</tr>");
			buffer.append("<tr>");
			buffer.append("<td>");
			buffer.append("<b>展会地点：</b>"+showAddress);
			buffer.append("</td>");
			buffer.append("</tr>");
			buffer.append("<tr>");
			buffer.append("<td height='5px'></td>");
			buffer.append("</tr>");
			buffer.append("<tr>");
			buffer.append("<td>");
			buffer.append("<b>姓名：</b>"+audience_name);
			buffer.append("</td>");
			buffer.append("</tr>");
			buffer.append("<tr>");
			buffer.append("<td>");
			buffer.append("<b>预登记号：</b>"+(9900000+audience_id));
			buffer.append("</td>");
			buffer.append("</tr>");
			buffer.append("<tr>");
			buffer.append("<td>");
			buffer.append("<img src='"+PropertiesUtil.getVal("weburl")+"/audienceCode.action?code="+ (9900000+audience_id) +"&barType=CODE39&checkCharacter=n&checkCharacterInText=n' width='400px' height='100px'/>");
			buffer.append("</td>");
			buffer.append("</tr>");
			buffer.append("</table>");
			buffer.append("</td>");
			buffer.append("</tr>");
			buffer.append("<tr>");
			buffer.append("<td height='10px'align='right'><a href='#' onclick='javascript:window.print();'>点击打印</a></td>");
			buffer.append("</tr>");
			buffer.append("<tr>");
			buffer.append("<td>");
			buffer.append("	<table cellpadding=2' cellspacing=2' style='border:1px solid #999999; padding:10px' width='800px'>");
			buffer.append("<tr>");
			buffer.append("<td>");
			buffer.append("<b>注意事项：</b>");
			buffer.append("</td>");
			buffer.append("</tr>");
			buffer.append("<tr>");
			buffer.append("<td style='padding-left: 20px'>");
			buffer.append("• 本邀请函仅限专业观众参观日期间使用（"+showTime+"）。");
			buffer.append("</td>");
			buffer.append("</tr>");
			buffer.append("<tr>");
			buffer.append("<td style='padding-left: 20px'>");
			buffer.append("• 此确认函不可转让，出售，只可由本人使用一次。请务必带上此确认函及个人名片(两张)前往展会现场，否则，主办方有权利收取您30元的门票费用。");
			buffer.append("</td>");
			buffer.append("</tr>");
			buffer.append("<tr>");
			buffer.append("<td style='padding-left: 20px'>");
			buffer.append("• 此信息只能使用一次，第二个持此相同信息的人将无法使用。如有同公司多人登记，请分别独立注册。"); 
			buffer.append("</td>");
			buffer.append("</tr>");
			buffer.append("<tr>");
			buffer.append("<td>");
			buffer.append("<b>如有疑问请联系我们：</b>");
			buffer.append("</td>");
			buffer.append("</tr>");
			buffer.append("<tr>");
			buffer.append("<td style='padding-left: 20px'>");
			buffer.append("电话："+showTel);
			buffer.append("</td>");
			buffer.append("</tr>");
			buffer.append("<tr>");
			buffer.append("<td style='padding-left: 20px'>");
			buffer.append("传真："+showFax);
			buffer.append("</td>");
			buffer.append("</tr>");
			buffer.append("<tr>");
			buffer.append("<td style='padding-left: 20px'>");
			buffer.append("Email："+showEmail);
			buffer.append("</td>");
			buffer.append("</tr>");
			buffer.append("<tr>");
			buffer.append("<td style='padding-left: 20px'>");
			buffer.append("网址：" + PropertiesUtil.getVal("weburl") +((showInfo.get("urlChannel")!=null&&!"".equals(showInfo.get("urlChannel").toString()))?("?source="+showInfo.get("urlChannel").toString()):""));
			buffer.append("</td>");
			buffer.append("</tr>");
			buffer.append("<tr height='10px'>");
			buffer.append("	<td></td>");
			buffer.append("</tr>");
			buffer.append("</table>");
			buffer.append("</td>");
			buffer.append("</tr>");
			buffer.append("</table>");
            
            email.setHtmlMsg(buffer.toString());
            email.send();
            
          //推荐朋友
            String[] friendEmails=emails.split("\\*");
            //判断是否有推荐用户
            if(friendEmails.length > 0){
	            HtmlEmail friendEmail = new HtmlEmail();
				friendEmail.setHostName(fromMailHost);
				friendEmail.setAuthentication(fromMail, fromMailPassword);
				friendEmail.setFrom(fromMail);
	            Vector<InternetAddress> friendEmailV = new Vector<InternetAddress>();
				
				
					for(int i=0;i<friendEmails.length;i++){
						if(friendEmails[i].contains("@")){
							//System.out.println(friendEmails[i]);
							friendEmailV.add(new InternetAddress(friendEmails[i]));
						}
					}
				
				friendEmail.setTo(friendEmailV);
				friendEmail.setCharset("UTF-8");
				friendEmail.setSubject("诚邀您参加<b>" + showInfo.get("showName") + "</b>展会");
				StringBuffer buffer1 = new StringBuffer(); 
				buffer1.append("<center>");
				buffer1.append("你的朋友<font color='green'>");
				buffer1.append(audience_name);
				if(audience_sex.equals("0")){
					buffer1.append("先生");
				}else if(audience_sex.equals("1")){
					
					buffer1.append("女士");
				}
				buffer1.append("</font>");
				buffer1.append("邀请你注册参加" + showInfo.get("showName") + "展会<br/>");
				buffer1.append("<a href='"+PropertiesUtil.getVal("weburl")+"/preAudienceQInfoAction.action?source="+(showInfo.get("urlChannel")!=null?showInfo.get("urlChannel").toString():"")+"'>请点击这里注册</a>");
				buffer1.append("</center>");
				friendEmail.setHtmlMsg(buffer1.toString());
	            friendEmail.send();
	            
            }
            
            Map request = (Map)ActionContext.getContext().get("request");
            //注册成功后,跳转到成功页面生成卡号,
            audience.setId(9900000 + audience_id);
            request.put("audience", audience);
            request.put("showInfo", showInfo);
            
    		return "success";
       } catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
		
		
		
		/*// 设置邮件服务器信息  
		 MailSenderInfo mailInfo = new MailSenderInfo();  
		 mailInfo.setMailServerHost("smtp.126.com");  
		 mailInfo.setMailServerPort("25");  
		 mailInfo.setValidate(true);    
		 // 邮箱用户名  
		 mailInfo.setUserName("sanyuesan00@126.com");  
		 // 邮箱密码 
		 mailInfo.setPassword("fyj2049694411");  
		 // 发件人邮箱 
		 mailInfo.setFromAddress("sanyuesan00@126.com");  
		 // 收件人邮箱  
		 mailInfo.setToAddress(toMail);  
		 // 邮件标题  
		 mailInfo.setSubject("测试Java程序发送邮件");  
		 // 邮件内容 
		 StringBuffer buffer = new StringBuffer();  
		 buffer.append("<font color='green'>您已登记成功。</font>\n");  
		 buffer.append("请您尽快打印相关文件，以便出席展会。<img src='cid:index' width='366' height='200'/>"); 
		 buffer.append("该邮件由系统自动发送，请勿回复");
		 mailInfo.setContent(buffer.toString());   
		 // 发送邮件  
		 SimpleMailSender sms = new SimpleMailSender();  
		 // 发送文体格式  
		 sms.sendTextMail(mailInfo);  
		 // 发送html格式  
		 SimpleMailSender.sendHtmlMail(mailInfo);  
		 System.out.println("邮件发送完毕"); */
		 
		 
	}
	
	//获取展会信息
	private String getShowInfoId() throws Exception{
		//获取展会信息
		String show_id = "";
		List<Map> showInfos = showInfoService.getShowInfoByTypeOrUrlChannel(null, source);
		if(null != showInfos && showInfos.size()>0){
			Map domain = (Map)showInfos.get(0);
			showInfo = domain;
			show_id = domain.get("id")!= null?domain.get("id").toString():"";
		}
		return show_id;
	}

	public String getEmails() {
		return emails;
	}

	public void setEmails(String emails) {
		this.emails = emails;
	}

	public void setAudienceService(AudienceService audienceService) {
		this.audienceService = audienceService;
	}
	
	public void setShowInfoService(ShowInfoService showInfoService) {
		this.showInfoService = showInfoService;
	}

	public void setMailInfoService(MailInfoService mailInfoService) {
		this.mailInfoService = mailInfoService;
	}

	public Audience getAudience() {
		return audience;
	}

	public void setAudience(Audience audience) {
		this.audience = audience;
	}

	public String getQuestioninfo() {
		return questioninfo;
	}

	public void setQuestioninfo(String questioninfo) {
		this.questioninfo = questioninfo;
	}

	public String getSource() {
		return source;
	}

	public void setSource(String source) {
		this.source = source;
	}

	public Map getShowInfo() {
		return showInfo;
	}

	public void setShowInfo(Map showInfo) {
		this.showInfo = showInfo;
	}
}
